package com.project_doctor.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.project_doctor.mapper.AnnouncementReceiverMapper;
import com.project_doctor.mapper.AnnouncementReplyMapper;
import com.project_doctor.pojo.AnnouncementReceiver;
import com.project_doctor.pojo.Dto.AnnRequest;
import com.project_doctor.pojo.SystemAnnouncement;
import com.project_doctor.service.AnnouncementReceiverService;
import com.project_doctor.service.SystemAnnouncementService;
import com.project_doctor.mapper.SystemAnnouncementMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.hutool.core.date.DateTime.now;

/**
* @author 龙龙与贝儿
* @description 针对表【t_system_announcement】的数据库操作Service实现
* @createDate 2025-06-03 10:32:05
*/
@Service
public class SystemAnnouncementServiceImpl extends ServiceImpl<SystemAnnouncementMapper, SystemAnnouncement>
    implements SystemAnnouncementService{
    @Autowired
    private SystemAnnouncementMapper systemAnnouncementMapper;
    @Autowired
    AnnouncementReceiverMapper receiverMapper;
    @Autowired
    AnnouncementReplyMapper replyMapper;

    @Autowired
    AnnouncementReceiverService receiverService;

    @Override
    public SystemAnnouncement getAnnById(Long id) {
        SystemAnnouncement announcement = systemAnnouncementMapper.getAnnByIdWithName(id);

        List<AnnouncementReceiver> receivers = receiverMapper.selectReceiversByAnnouncementId(id);
        announcement.setReceiverIds(receivers.stream()
                .map(AnnouncementReceiver::getReceiverId)
                .collect(Collectors.toList()));

        return announcement;
    }

    @Override
    public List<SystemAnnouncement> getAnnouncementList(AnnRequest annRequest) {
        List<SystemAnnouncement> systemAnnouncements = systemAnnouncementMapper.selectAllWithNameAndRole(annRequest);
        return systemAnnouncements;
    }


    @Override
    @Transactional
    public void updateAnnouncement(SystemAnnouncement systemAnnouncement) {
        systemAnnouncement.setStatus(1);
        systemAnnouncementMapper.updateById(systemAnnouncement); // 最简单的方式
        // 更新接收人（先删除旧的）
        receiverMapper.delete(new QueryWrapper<AnnouncementReceiver>()
                .eq("announcement_id", systemAnnouncement.getId()));

        if (systemAnnouncement.getReceiverIds() != null && !systemAnnouncement.getReceiverIds().isEmpty()) {
            List<AnnouncementReceiver> receivers = systemAnnouncement.getReceiverIds().stream()
                    .map(receiverId -> new AnnouncementReceiver(systemAnnouncement.getId(), receiverId,systemAnnouncement.getDoctorIdSend(), 0, null))
                    .collect(Collectors.toList());
            receiverService.saveBatch(receivers);

        }
    }

    @Override
    @Transactional
    public void newAnnouncement(SystemAnnouncement systemAnnouncement) {
        // 初始化公告对象并设置状态
        SystemAnnouncement announcement = new SystemAnnouncement();
        BeanUtils.copyProperties(systemAnnouncement, announcement);
        announcement.setStatus(1); // 注意：这里应该设置到announcement对象而不是原对象

        // 插入公告，此时数据库会生成ID并回填到announcement对象
        systemAnnouncementMapper.insert(announcement);

        // 保存接收人
        if (announcement.getReceiverIds() != null && !announcement.getReceiverIds().isEmpty()) {
            List<AnnouncementReceiver> receivers = announcement.getReceiverIds().stream()
                    .map(receiverId -> new AnnouncementReceiver(
                            announcement.getId(), // 使用插入后生成的公告ID
                            receiverId,
                            announcement.getDoctorIdSend(),
                            0,                  // 未读状态
                            null                // 阅读时间设为null
                    ))
                    .collect(Collectors.toList());

            // 调用Service层批量保存接收人
            receiverService.saveBatch(receivers);
        }
    }

    @Override
    @Transactional
    public void batchNewAnnouncement(List<SystemAnnouncement> dataList) {
        // 1. 批量插入公告
        systemAnnouncementMapper.batchNewAnnouncement(dataList);

        // 2. 处理每个公告的接收人
        for (SystemAnnouncement systemAnnouncement : dataList) {
            // 确保公告ID存在
            if (systemAnnouncement.getId() != null &&
                    systemAnnouncement.getReceiverIds() != null &&
                    !systemAnnouncement.getReceiverIds().isEmpty()) {

                // 3. 构建接收人关系列表
                List<AnnouncementReceiver> receivers = systemAnnouncement.getReceiverIds().stream()
                        .filter(Objects::nonNull) // 过滤空值
                        .map(receiverId -> {
                            AnnouncementReceiver receiver = new AnnouncementReceiver();
                            receiver.setAnnouncementId(systemAnnouncement.getId());
                            receiver.setReceiverId(receiverId);
                            receiver.setSenderId(systemAnnouncement.getDoctorIdSend());
                            receiver.setReadStatus(0); // 未读状态
                            return receiver;
                        })
                        .collect(Collectors.toList());

                // 4. 批量保存接收人关系
                if (!receivers.isEmpty()) {
                    receiverService.saveBatch(receivers);
                }
            }
        }
    }


    @Override
    public List<SystemAnnouncement> listForReceiver(Long receiverId, Integer status) {
        // 构建查询条件
        QueryWrapper<SystemAnnouncement> wrapper = new QueryWrapper<>();

        // 使用MyBatis-Plus安全的嵌套查询替代inSql
        List<Long> announcementIds = new LambdaQueryChainWrapper<>(receiverMapper)
                .select(AnnouncementReceiver::getAnnouncementId)
                .eq(AnnouncementReceiver::getReceiverId, receiverId)
                .list()
                .stream()
                .map(AnnouncementReceiver::getAnnouncementId)
                .collect(Collectors.toList());

        // 添加公告ID条件
        if (!announcementIds.isEmpty()) {
            wrapper.in("id", announcementIds);
        } else {
            // 如果没有找到相关公告ID，直接返回空列表
            return Collections.emptyList();
        }

        // 添加状态筛选条件
        if (status != null) {
            wrapper.eq("status", status);
        }

        // 按发布时间降序排列
        wrapper.orderByDesc("publish_time");

        // 执行查询
        return systemAnnouncementMapper.selectList(wrapper);
    }



}




